#include "StaticFileCommand.h"
#include "Environment.h"
#include "ResourceManager.h"
#include <iostream>
#include <fstream>

namespace phnq
{
	namespace phnqlets
	{
		void StaticFileCommand::execute(string path, map<string,string> params, processor_response *response)
		{
			string resPath = ResourceManager::getInstance()->findResource(path);
			if(resPath == "")
			{
				response->status = STATUS_NOT_FOUND;
			}
			else
			{
				set<string>* forbiddenPaths = getForbiddenPaths();

				for(set<string>::reverse_iterator it=forbiddenPaths->rbegin(); it != forbiddenPaths->rend(); it++)
				{
					string fp = *it;

					if(fp < resPath)
					{
						if(resPath.find(fp) == 0)
							response->status = STATUS_FORBIDDEN;

						break;
					}
				}

				if(response->status == STATUS_OK)
					response->bodyStream = new ifstream(resPath.c_str());
			}
		}

		set<string>* StaticFileCommand::getForbiddenPaths()
		{
			static set<string> paths;
			
			return &paths;
		}

		void StaticFileCommand::addForbiddenPath(string path)
		{
			if(path.length() > 1 && path.at(path.length()-1) != '/')
				path += "/";
				
			getForbiddenPaths()->insert(path);
		}
	}
}
